<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\services\system;

use common\models\system\AdminDept;
use common\models\system\AdminPos;
use common\models\system\AdminRole;
use yii\db\Exception;

class AdminService
{
    /**
     * 更新人员角色信息
     * @param $adminId
     * @param string|int|array $roleIds
     * @return bool
     */
    public static function updateAdminRoleIds($adminId, $roleIds): bool
    {
        if (!$adminId) return false;
        AdminRole::deleteAll(['admin_id' => $adminId]);

        $data = [];
        $roleIds = $roleIds ? array_unique(is_array($roleIds) ? $roleIds : explode(',', $roleIds)) : [];
        foreach ($roleIds as $roleId) {
            if ($roleId) $data[] = [$adminId, $roleId];
        }
        if (!$data) return true;

        try {
            \Yii::$app->db->createCommand()->batchInsert(AdminRole::tableName(), ['admin_id', 'role_id'], $data)->execute();
            return true;
        } catch (Exception $exception) {
            return false;
        }
    }

    /**
     * 更新人员岗位信息
     * @param $adminId
     * @param string|int|array $posIds
     * @return bool
     */
    public static function updateAdminPostIds($adminId, $posIds): bool
    {
        if (!$adminId) return false;
        AdminPos::deleteAll(['admin_id' => $adminId]);

        $data = [];
        $posIds = $posIds ? array_unique(is_array($posIds) ? $posIds : explode(',', $posIds)) : [];
        foreach ($posIds as $posId) {
            if ($posId) $data[] = [$adminId, $posId];
        }
        if (!$data) return true;

        try {
            \Yii::$app->db->createCommand()->batchInsert(AdminPos::tableName(), ['admin_id', 'pos_id'], $data)->execute();
            return true;
        } catch (Exception $exception) {
            return false;
        }
    }

    /**
     * 更新人员部门信息
     * @param $adminId
     * @param string|int $deptId
     * @return bool
     */
    public static function updateAdminDeptIds($adminId, $deptId): bool
    {
        if (!$adminId) return false;
        if (!$deptId) {
            AdminDept::deleteAll(['admin_id' => $adminId]);
            return true;
        }
        $model = AdminDept::findOne(['admin_id' => $adminId]);
        if ($model && $model->dept_id == $deptId) return true;
        if (!$model) $model = new AdminDept();
        $model->admin_id = $adminId;
        $model->dept_id = $deptId;
        if ($model->save(false)) return true;
        return false;
    }
}
